package com.xu.config;


import com.xu.pojo.User;
import com.xu.pojo.UserDto;
import com.xu.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl userService;

    //当需要权限认证时执行
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //System.out.println("===doGetAuthorizationInfo===");
        Subject subject = SecurityUtils.getSubject();
        UserDto user = (UserDto)subject.getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(user.getRoles());
        return info;
    }



    //当调用Subject currentUser = SecurityUtils.getSubject();  currentUser.login(token);时执行
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //System.out.println("===doGetAuthenticationInfo===");
        UsernamePasswordToken usertoken = (UsernamePasswordToken) authenticationToken;
        User user = userService.queryUserByID(Integer.valueOf(usertoken.getUsername()).intValue());
        if (user==null){
            return null;
        }
        UserDto userDto = new UserDto(user);
        return new SimpleAuthenticationInfo(userDto,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),"");
    }
}
